import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { selectReddit, fetchPostsIfNeeded, invalidateReddit } from '../actions';
import Picker from '../components/Picker';
import Posts from '../components/Posts';

class App extends Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
        this.handleRefreshClick = this.handleRefreshClick.bind(this);
    }

    componentDidMount() {
        console.log('执行componentDidMount');
        const { dispatch, selectedReddit } = this.props;
        // 发起REQUEST_POSTS这个action
        dispatch(fetchPostsIfNeeded(selectedReddit));
    }

    //刷新页面时，组件中被绑定的props变了，会执行 componentWillReceiveProps
    componentWillReceiveProps(nextProps) {
        console.log('执行componentWillReceiveProps', nextProps);
        // 在关键词改变时会执行dispatch(fetchPostsIfNeeded(selectedReddit))，所以又发起了REQUEST_POSTS这个action
        if (nextProps.selectedReddit !== this.props.selectedReddit) {
            const { dispatch, selectedReddit } = nextProps;
            dispatch(fetchPostsIfNeeded(selectedReddit));
        }
    }

    //切换下拉框事件的注册函数
    handleChange(nextReddit) {
        // 发起SELECT_REDDIT这个action
        this.props.dispatch(selectReddit(nextReddit));
    }

    //刷新按钮点击事件的注册函数
    handleRefreshClick(e) {
        e.preventDefault();

        const { dispatch, selectedReddit } = this.props;
        dispatch(invalidateReddit(selectedReddit));
        dispatch(fetchPostsIfNeeded(selectedReddit));
    }

    render() {
        const { selectedReddit, posts, isFetching, lastUpdated } = this.props;
        const isEmpty = posts.length === 0;
        const message = isFetching ? <h2>Loading...</h2> : <h2>Empty.</h2>;
        return (
            <div>
                <Picker
                    value={selectedReddit}
                    onChange={this.handleChange}
                    options={['reactjs', 'frontend']}
                />
                <p>
                    {lastUpdated &&
                    <span>
              Last updated at {new Date(lastUpdated).toLocaleTimeString()}.
                        {' '}
                    </span>
                    }
                    {!isFetching &&
                    <a
                        href="#"
                        onClick={this.handleRefreshClick}
                    >
                        Refresh
                    </a>
                    }
                </p>
                {isEmpty ? message : <div style={{ opacity: isFetching ? 0.5 : 1 }}>
                    <Posts posts={posts} />
                </div>
                }
            </div>
        );
    }
}

App.propTypes = {
    selectedReddit: PropTypes.string.isRequired,
    posts: PropTypes.array.isRequired,
    isFetching: PropTypes.bool.isRequired,
    lastUpdated: PropTypes.number,
    dispatch: PropTypes.func.isRequired,
};

function mapStateToProps(state) {
    const { selectedReddit, postsByReddit } = state;
    const {
        isFetching,
        lastUpdated,
        items: posts,
    } = postsByReddit[selectedReddit] || {
        isFetching: true,
        items: [],
    };

    return {
        selectedReddit,
        posts,
        isFetching,
        lastUpdated,
    };
}

// ./node_modules/react-redux/src/components/connect.js
// 函数定义:
// function connect(mapStateToProps, mapDispatchToProps, mergeProps, options = {})
// 分析代码可知: 无 mapDispatchToProps 参数, 则设置默认的 defaultMapDispatchToProps = dispatch => ({ dispatch })
export default connect(mapStateToProps)(App);
